#import "AppDelegate.h"

#import "LoginViewController.h"
#import "WXApi_.h"
#import "AppDelegate+EaseMob.h"

#import <TencentOpenAPI/TencentOAuth.h>
#import "TencentAppMacro.h"
#import "WXHelper.h"
#import "WeiboHelper.h"
#import "WeiboSDK.h"
#import "WeiboMacro.h"

#import "ShareMethods.h"


//两次提示的默认间隔
const CGFloat kDefaultPlaySoundInterval = 3.0;

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *str = [accountDefaults objectForKey:@"uid"];
    if ([str isEqual:[NSNull null]] || str.length == 0) {
        [accountDefaults setObject:@"0" forKey:@"uid"];
    }
    [accountDefaults setObject:@"1" forKey:@"phone"];
    
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        
        UIUserNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        
    }else
        
        
        
    {
        
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
        
    }
    
    
    _connectionState = eEMConnectionConnected;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginStateChange:)
                                                 name:KNOTIFICATION_LOGINCHANGE
                                               object:nil];
    
    //    if ([UIDevice currentDevice].systemVersion.floatValue >= 7.0) {
    //        [[UINavigationBar appearance] setBarTintColor:RGBACOLOR(78, 188, 211, 1)];
    //        [[UINavigationBar appearance] setTitleTextAttributes:
    //         [NSDictionary dictionaryWithObjectsAndKeys:RGBACOLOR(245, 245, 245, 1), NSForegroundColorAttributeName, [UIFont fontWithName:@ "HelveticaNeue-CondensedBlack" size:21.0], NSFontAttributeName, nil]];
    //    }
    
    
    
    // 初始化环信SDK，详细内容在AppDelegate+EaseMob.m 文件中
    [self easemobApplication:application didFinishLaunchingWithOptions:launchOptions];
    //[WXApi registerApp:@"wxf96508ee8fc3e05b" withDescription:@"demo 2.0"];
    
    [WXApi registerApp:kWXAppKey];
    [WeiboSDK registerApp:kWeiboAppKey];
    [WeiboSDK enableDebugMode:YES];
    
    return YES;
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //    if (_mainController) {
    //        [_mainController jumpToChatList];
    //    }
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    //    if (_mainController) {
    //        [_mainController jumpToChatList];
    //    }
}

#pragma mark - 登陆状态改变

-(void)loginStateChange:(NSNotification *)notification
{
    
    BOOL isAutoLogin = [[[EaseMob sharedInstance] chatManager] isAutoLoginEnabled];
    BOOL loginSuccess = [notification.object boolValue];
    
    UITabBarController *rootTabbar = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    if (![rootTabbar isKindOfClass:[UITabBarController class]]) {
        return;
    }
    
    NSMutableArray *vcs = [rootTabbar.viewControllers mutableCopy];
    UINavigationController *nav = vcs[2];
    
    if (isAutoLogin || loginSuccess) {//登陆成功加载主窗口控制器
        //加载申请通知的数据
        [[ApplyViewController shareController] loadDataSourceFromLocalDB];
        
        if (_chatController == nil) {
            _chatController = [[ChatListViewController alloc] init];
            
        }
        
        //nav.viewControllers = @[_chatController];
        
        
    }
    
    else{//登陆失败加载登陆页面控制器
        _chatController = nil;
        NSLog(@"强制登录....");
        LoginViewController *loginController = [[LoginViewController alloc] init];
        //nav.viewControllers = @[loginController];
    }
    
    //    rootTabbar.viewControllers = vcs;
    //
    //    NSArray *itemArr = rootTabbar.tabBar.items;
    //
    //    UITabBarItem *item = itemArr[2];
    //    UIImage * selectedImage = [[UIImage imageNamed:[NSString stringWithFormat:@"menu%i_focus",2]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    //    UIImage * unselectedImage = [[UIImage imageNamed:[NSString stringWithFormat:@"menu%i",2]]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    //    [item setFinishedSelectedImage:selectedImage
    //           withFinishedUnselectedImage:unselectedImage];
    
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    NSLog(@"sourceApplication:%@",sourceApplication);
    if ([sourceApplication isEqualToString:@"com.tencent.mqq"]) {
        return [TencentOAuth HandleOpenURL:url];
    }
    else if ([sourceApplication isEqualToString:@"com.tencent.xin"]){
        //return [WXApi handleOpenURL:url delegate:[WXHelper shareInstance]];
        return [ShareMethods handleOpenURL:url];
    }
    else if ([[NSString stringWithFormat:@"%@",url] rangeOfString:@"UPPayDemo"].location != NSNotFound){
        
        return [ShareMethods handleOpenURL:url];
    }
    else {
        return [WeiboSDK handleOpenURL:url delegate:[WeiboHelper shareInstance]];
    }
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    
    NSString *urlString = [NSString stringWithFormat:@"%@",url];
    NSLog(@"urlString:%@",urlString);
    NSRange range = [urlString rangeOfString:@"tencent"];
    if (range.length > 0) {
        return [TencentOAuth HandleOpenURL:url];
    }
    else {
        return [WXApi handleOpenURL:url delegate:[WXHelper shareInstance]];
        //return [WeiboSDK handleOpenURL:url delegate:[WeiboHelper shareInstance]];
        //return [WeiboSDK handleOpenURL:url delegate:[WeiboHelper shareInstance]];
    }
    
}

+(AppDelegate *)sharedDelegate {
    
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

- (void)onReq:(BaseReq*)req
{
    /*
            39      onReq是微信终端向第三方程序发起请求，要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时，会切回到微信终端程序界面。
            40      */
    NSLog(@"req:%@",req);
}

- (void)onResp:(BaseResp*)resp
{
    /*
            46      如果第三方程序向微信发送了sendReq的请求，那么onResp会被回调。sendReq请求调用后，会切到微信终端程序界面。
            47      */
    NSLog(@"resq:%@",resp);
}



@end
